package com.yuexun.dhdoctor.module.email.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.Contract.bean.People;
import com.yuexun.dhdoctor.module.commun.adapter.AddMemberAdapter;
import com.yuexun.dhdoctor.module.commun.ui.Act_Choice_Member;
import com.yuexun.dhdoctor.module.email.adapter.DraftEdtFileAdapter;
import com.yuexun.dhdoctor.module.email.bean.MailDataBean;
import com.yuexun.dhdoctor.module.email.bean.MailFileDataBean;
import com.yuexun.dhdoctor.module.email.bean.SendBean;
import com.yuexun.dhdoctor.module.email.bean.UploadBean;
import com.yuexun.dhdoctor.module.email.model.impl.SendModel;
import com.yuexun.dhdoctor.module.email.model.impl.UploadModel;
import com.yuexun.dhdoctor.module.email.presenter.ISendPresenter;
import com.yuexun.dhdoctor.module.email.presenter.IUploadPresenter;
import com.yuexun.dhdoctor.module.email.presenter.impl.SendPresenter;
import com.yuexun.dhdoctor.module.email.presenter.impl.UploadPresenter;
import com.yuexun.dhdoctor.module.email.ui.view.ISendView;
import com.yuexun.dhdoctor.module.email.ui.view.IUploadView;
import com.yuexun.dhdoctor.util.GetPathFromUri4kitkat;
import com.yuexun.dhdoctor.widget.ActionSheetDialog;
import com.yuexun.dhdoctor.widget.FixedSwipeListView;
import com.yuexun.dhdoctor.widget.ProgressWebView;
import com.yuexun.dhdoctor.widget.UploadDialog;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by work-jx on 2016/8/3.
 */
public class Act_TransmitMail extends BaseKJActivity implements ISendView, IUploadView {
    @Bind(R.id.grid)
    GridView grid;
    @Bind(R.id.draft_title_edt)
    EditText draftTitleEdt;
    @Bind(R.id.draft_file_list)
    FixedSwipeListView draftFileList;
    //    @Bind(R.id.reply_cintent_edt)
//    EditText replyCintentEdt;
    @Bind(R.id.webview)
    ProgressWebView webview;
    @Bind(R.id.title_tv)
    TextView title_tv;

    private MailDataBean mailDataBean = new MailDataBean();
    private ArrayList<People> usersBeans_origin = new ArrayList<>();
    private ArrayList<MailFileDataBean> mailFileDataBeans = new ArrayList<>();
    private AddMemberAdapter adapter;

    private DraftEdtFileAdapter adapter_file;

    private ISendPresenter presenter;
    private IUploadPresenter presenter_upload;

    private UploadDialog uploadDialog;

    private String web_content = "";

    //附件原路径
    private String img_path;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_draftedt);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        title_tv.setText("转发");
        presenter = new SendPresenter(new SendModel(), this);
        mailDataBean = (MailDataBean) getIntent().getExtras().getSerializable("maillist");
        mailFileDataBeans = (ArrayList<MailFileDataBean>) getIntent().getExtras().getSerializable("filelist");
        draftTitleEdt.setText("【转发】" + mailDataBean.getTitle());

        adapter_file = new DraftEdtFileAdapter(this, mailFileDataBeans);
        draftFileList.setAdapter(adapter_file);

        init_web();
        web_content = mailDataBean.getContent().replace("＜", "<").replace("＞", ">");
        web_content = "<div contenteditable=true id=mail_content>" + web_content;
        webview.loadDataWithBaseURL(AppConfig.TEXTVIEW_WEBVIEW, web_content, "text/html", "UTF-8", null);

        uploadDialog = new UploadDialog(this);
        presenter_upload = new UploadPresenter(new UploadModel(), this);
    }

    private void init_web() {
        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webview.getSettings().setUseWideViewPort(false);
        webview.getSettings().setDisplayZoomControls(false);
        webview.setInitialScale(300);
        webview.setWebViewClient(new CustomWebViewClient());
        webview.setWebChromeClient(new CustomWebChromeView());
        webview.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj");
//        webview.setSaveEnabled(false);
    }

    final class InJavaScriptLocalObj {
        @JavascriptInterface
        public void showSource(String html) {
            web_content = html;
            send();
        }
    }

    private class CustomWebViewClient extends WebViewClient {


        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }


        @Override
        public void onPageFinished(WebView view, String url) {

            super.onPageFinished(view, url);
        }
    }

    private class CustomWebChromeView extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {

            super.onProgressChanged(view, newProgress);
        }
    }

    private void setGridView() {

        int size = usersBeans_origin.size();

        int length = 80;

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int gridviewWidth = (int) (size * (length + 8) * density);
        int itemWidth = (int) (length * density);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
        grid.setLayoutParams(params); // 重点
        grid.setColumnWidth(itemWidth); // 重点
        grid.setHorizontalSpacing(5); // 间距
        grid.setStretchMode(GridView.NO_STRETCH);
        grid.setNumColumns(size); // 重点

        adapter = new AddMemberAdapter(grid, usersBeans_origin, R.layout.item_send_addmember);
        grid.setAdapter(adapter);
    }

    @OnClick({R.id.back, R.id.draft_send, R.id.draft_add_sendmember, R.id.draft_add_attachment})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.draft_send:
                webview.loadUrl("javascript:window.local_obj.showSource(document.getElementById('mail_content').innerHTML);");
                break;
            case R.id.draft_add_sendmember:
//                Bundle bundle = new Bundle();
//                Intent intent = new Intent(this, Act_Choice_People.class);
//                bundle.putSerializable("persons", usersBeans_origin);
//                intent.putExtras(bundle);
//                aty.startActivityForResult(intent, 1);
                Bundle bundle = new Bundle();
                Intent intent = new Intent(this, Act_Choice_Member.class);
                bundle.putSerializable("persons", usersBeans_origin);
                bundle.putString("title", "");
                bundle.putInt("isSelectMe", 1);
                bundle.putString("type", "多选");
                intent.putExtras(bundle);
                aty.startActivityForResult(intent, 1);
                break;
            case R.id.draft_add_attachment:
                select_file();
                break;
        }
    }

    private void select_file() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, 1);
    }

    private void send() {
        if (usersBeans_origin.size() != 0 && !"".equals(draftTitleEdt.getText().toString()) && !"".equals(web_content)) {
            submitDialog();
        } else {
            ViewInject.toast("请检查标题,正文,人员是否填写");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 10000:
                usersBeans_origin = (ArrayList<People>) data.getExtras().getSerializable("persons");
                setGridView();
                break;
            case Activity.RESULT_OK:
                Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
                img_path = GetPathFromUri4kitkat.getPath(this, uri);
                presenter_upload.uploadFile(img_path);
                break;
            default:
                break;
        }
    }

    @Override
    public void sendMail(SendBean s) {
        if (s.getStatus().equals("200")) {
            ViewInject.toast("发送成功");
            finish();
        } else {
            ViewInject.toast("发送失败");
        }
    }

    @Override
    public void uploadDialogStatus(int status) {
        switch (status) {
            case AppConfig.SHOW_DIALOG:
                uploadDialog.setCanceledOnTouchOutside(false);
                uploadDialog.show();
                break;
            case AppConfig.DISMISS_DIALOG:
                uploadDialog.dismiss();
                break;

        }
    }

    @Override
    public void updateFile(UploadBean uploadBean) {
        uploadBean.getData().get(0).setFileUrl(img_path);
        mailFileDataBeans.add(uploadBean.getData().get(0));
        adapter_file.notifyDataSetChanged();
    }

    private void submitDialog() {
        new ActionSheetDialog(aty)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(false)
                .setTitle("确认发送")
                .addSheetItem("存草稿", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Submit(2);
                            }
                        })
                .addSheetItem("发送", ActionSheetDialog.SheetItemColor.Red,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Submit(1);
                            }
                        }).show();
    }

    private void Submit(int type) {
        StringBuilder ids = new StringBuilder();
        StringBuilder name = new StringBuilder();
        for (int i = 0; i < usersBeans_origin.size(); i++) {
            ids.append(usersBeans_origin.get(i).getUserId()).append(";");
            name.append(usersBeans_origin.get(i).getUserName()).append(";");
        }
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("type", type + "");
        params.put("title", draftTitleEdt.getText().toString());
        params.put("content", web_content);
        params.put("recipients", name.toString());
        params.put("recipients_ids", ids.toString());
        if (mailFileDataBeans.size() > 0) {
            String file = mailFileDataBeans.get(0).getFileUuid();
            for (int i = 1; i < mailFileDataBeans.size(); i++) {
                file = file + ";" + mailFileDataBeans.get(i).getFileUuid();
            }
            params.put("fileURL", file);
        }
        presenter.sendMail(params);
    }
}
